package com.york.tinyrpc.protoss.server;

import com.york.tinyrpc.protoss.model.TinyRpcRequest;
import com.york.tinyrpc.protoss.model.TinyRpcResponse;
import com.york.tinyrpc.protoss.registry.LocalRegistry;

import java.lang.reflect.Method;

/**
 * protoss版本：优化代码
 * 抽象出ServerHandler
 * 封装公有的方法
 */
public abstract class BaseServerHandler {

    /**
     * 根据request获取response
     *
     * @param rpcRequest
     * @return
     * @throws Throwable
     */
    public static TinyRpcResponse getResponseByRequest(TinyRpcRequest rpcRequest) throws Throwable {
        TinyRpcResponse rpcResponse = new TinyRpcResponse();
        try {
            // 获取要调用的服务实现类，通过反射调用
            Class<?> implClass = LocalRegistry.getService(rpcRequest.getServiceName());
            Method method = implClass.getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
            Object result = method.invoke(implClass.newInstance(), rpcRequest.getArgs());
            // 封装返回结果
            rpcResponse.setData(result);
            rpcResponse.setDataType(method.getReturnType());
            rpcResponse.setMessage("ok");
        } catch (Exception e) {
            e.printStackTrace();
            rpcResponse.setMessage(e.getMessage());
            rpcResponse.setException(e);
        }
        return rpcResponse;
    }
}
